﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Collections.Specialized;
using BSCMFF.Core.DataAccessLayer;
using BSCMFF.Core.BusinessLayer;
using BSCMFF.Core.Exceptions.Database;


namespace BSCMFF.Core.MembershipDataProvider
{
    public class EntityMembershipDataProvider : MembershipProvider
    {
        public override void Initialize(string name, NameValueCollection config)
        {

            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (String.IsNullOrEmpty(name))
            {
                name = "EntityMembershipDataProvider";
            }

            //if (String.IsNullOrEmpty(config["description"]))
            //{
            //    config.Remove("description");
            //    config.Add("description", "Generic Database Provider");
            //}

            base.Initialize(name, config);

            //if (config["connectionStringName"] == null)
            //{
            //    // default to DataEngine
            //    config["connectionStringName"] = "DataSource";
            //}

            //connStringName = config["connectionStringName"];
            //config.Remove("connectionStringName");

            //// loading connection string
            //connString = ConfigurationManager.ConnectionStrings[connStringName].ConnectionString;

            //if (config["parmPrefix"] == null)
            //{
            //    // default
            //    config["parmPrefix"] = "@";
            //}

            //parmPrefix = config["parmPrefix"];
            //config.Remove("parmPrefix");

            //// loading database
            //string providerName = ConfigurationManager.ConnectionStrings[connStringName].ProviderName;
            //database = DbProviderFactories.GetFactory(providerName);

            //// creating connection when knowing the database
            //if (connection == null)
            //{
            //    connection = database.CreateConnection();
            //    connection.ConnectionString = connString;
            //}

            //// Throw an exception if unrecognized attributes remain
            //if (config.Count > 0)
            //{
            //    string attr = config.GetKey(0);
            //    if (!String.IsNullOrEmpty(attr))
            //    {
            //        throw new ProviderException("Unrecognized attribute: " + attr);
            //    }
            //}
        }

        private const int DefaultMinRequiredPasswordLength = 8;
        private const string EmailPattern = @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$";

        private string applicationName = "BSC MFF", connectionString;
        //private NameValueCollection configuration;

        public override string ApplicationName
        {
            get { return this.applicationName; }
            set { this.applicationName = value; }
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            if (ValidateUser(username, oldPassword))
            {
                BSCEntities context = new BSCEntities();
                User user = (from u in context.Users
                            where u.Login == username
                            select u).SingleOrDefault();

                user.Password = ComputeSHA512(newPassword);

                try
                {
                    context.SaveChanges();
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                    throw new InconsistentDatabaseException("Couldn't change password: " + ex.Message);
                    
                }

            }
            else
            {
                return false;
            }
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }

        public override bool EnablePasswordReset
        {
            get { return true; }
        }

        public override bool EnablePasswordRetrieval
        {
            get { return false; }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public IList<User> MyGetAllUsers()
        {
            //throw new NotImplementedException();
            BSCEntities context = new BSCEntities();
            var users = (from u in context.Users
                         select u).ToList();

            return users;           
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            //UserManager um = new UserManager();
            //User u = um.GetUserByLogin(username);

            //return u.Password;
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            UserManager um = new UserManager();
            User u = um.GetUserByLogin(username);

            DateTime dt = DateTime.Today;

            MembershipUser mu = new MembershipUser("EntityMembershipDataProvider", username, null, u.Email, "", "", true, false, dt, dt, dt, dt, dt);

            return mu;
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new NotImplementedException();
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return 0; }
        }

        public override int MinRequiredPasswordLength
        {
            get { return 1; }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new NotImplementedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { return false; }
        }

        public override bool RequiresUniqueEmail
        {
            get { throw new NotImplementedException(); }
        }

        public override string ResetPassword(string username, string answer)
        {
            BSCEntities context = new BSCEntities();
            User user = (from u in context.Users
                         where u.Login == username
                         select u).SingleOrDefault();

            string newpassword = GeneratePassword();

            string hashedNewPassword = ComputeSHA512(newpassword);
            user.Password = hashedNewPassword;

            try
            {
                context.SaveChanges();
                List<string> email = new List<string>();
                email.Add(user.Email);
                EmailProvider.EmailProvider.SendEmailsThroughGmail(email, "Password Reset", "Your Password has been reseted. New Password: " + hashedNewPassword);
                
            }
            catch (Exception ex)
            {
                throw new InconsistentDatabaseException("Couldn't reset password: " + ex.Message);

            }

            return "";
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }

        public override bool ValidateUser(string username, string password)
        {
            //if (!ComputeSHA512(password).Equals(u.Password, StringComparison.InvariantCultureIgnoreCase))
            //    //if(password != u.Password) //zatial nehashujeme
            //    return false; // invalid password

            if(string.IsNullOrEmpty(password))
                return false;

            string hashedPassword = ComputeSHA512(password);


            BSCEntities context = new BSCEntities();
            
            User validatedUser = (from u in context.Users
                                  where u.Login == username //&& u.Password == password
                                  select u).FirstOrDefault();
            //return validatedUser == null ? false : true;

            if (validatedUser != null && hashedPassword.Equals(validatedUser.Password, StringComparison.InvariantCultureIgnoreCase))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool MyChangePassword(string login, string oldPassword, string newPassword, string confirmPassword)
        {
            //if(ValidateUser(login, oldPassword)
            //{
                return ChangePassword(login, oldPassword, newPassword);
            //}

            //return true;
        }

        /// <summary>
        /// Computes hash for password
        /// </summary>
        /// <param name="s">unhashed password</param>
        /// <returns>hashed password</returns>
        private static string ComputeSHA512(string s)
        {
            if (string.IsNullOrEmpty(s)) throw new ArgumentNullException();
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(s);
            buffer = System.Security.Cryptography.SHA512Managed.Create().ComputeHash(buffer);
            return System.Convert.ToBase64String(buffer).Substring(0, 86); // strip padding
        }

        protected string GeneratePassword()
        {
            int passwordLength = 8;
            string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";
            char[] chars = new char[passwordLength];
            Random rd = new Random();

            for (int i = 0; i < passwordLength; i++)
            {
                chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
            }

            return new string(chars);
        }
    }
}
